﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace Milkify.Input
{
    public class PageFocusHelper
    {
        private ItemsControl mItemsControl;
        private string mItemsControlElementName;

        public IInputElement DefaultFocusElement { get; private set; }
        public IInputElement FocusElement { get; set; }

        public PageFocusHelper(Page page)
            : this(page, null)
        {
        }

        public PageFocusHelper(Page page, IInputElement defaultElement)
        {
            DefaultFocusElement = defaultElement;
            FocusElement = null;

            page.Loaded += new RoutedEventHandler(Page_Loaded);
        }

        public PageFocusHelper(Page page, ItemsControl itemsControl, string elementName)
            : this(page, null)
        {
            mItemsControl = itemsControl;
            mItemsControlElementName = elementName;

            mItemsControl.Loaded += new RoutedEventHandler(ItemsControl_Loaded);
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (FocusElement != null)
                FocusElement.Focus();
            else if (DefaultFocusElement != null)
                DefaultFocusElement.Focus();
        }

        private void ItemsControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (FocusElement == null)
            {
                // Focus the first element when the items control's UI has been generated.
                mItemsControl.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
                ItemContainerGenerator_StatusChanged(mItemsControl.ItemContainerGenerator, EventArgs.Empty);
            }
        }

        private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            if (mItemsControl.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
            {
                if (mItemsControlElementName != null)
                {
                    if (FocusHelper.FocusFirstItem(mItemsControl, mItemsControlElementName))
                        mItemsControl.ItemContainerGenerator.StatusChanged -= new EventHandler(ItemContainerGenerator_StatusChanged);
                }
                else
                {
                    if (FocusHelper.FocusFirstItem(mItemsControl))
                        mItemsControl.ItemContainerGenerator.StatusChanged -= new EventHandler(ItemContainerGenerator_StatusChanged);
                }
            }
        }
    }
}
